<template>
  <wd-swipe-action>
    <template #default>
      <view class="product">
        <view class="product-checkbox">
          <wd-checkbox
            :model-value="isSelected"
            @update:model-value="selectHandle"
          />
        </view>
        <view class="product-image">
          <v-image
            height="190rpx"
            width="190rpx"
            border-radius="8rpx"
            :src="product.image"
            mode="aspectFill"
            @click="selectHandle"
          />
          <view v-if="statusText" class="image-mask">
            <view class="product-status">
              {{ statusText }}
            </view>
          </view>
        </view>
        <view class="product-info">
          <view class="name" @click="navigateToDetails">
            {{ product.title }}
          </view>
          <view class="spec-list" @click="$emit('select-sku')">
            <view
              v-for="(spec, index) in product.spec_info"
              :key="index"
              class="spec-item"
            >
              <view>
                {{ spec.value }}
              </view>
              <wd-icon name="arrow-down" size="16rpx" color="#333333" />
            </view>
          </view>
          <view class="inventory">
            {{ inventory }}
          </view>
          <view class="footer">
            <v-price size="32rpx" :price="product.sell_price" />
            <v-input-number
              v-if="!statusText"
              :model-value="product.quantity"
              action
              :precision="0"
              :min="1"
              :max="product.inventory ?? undefined"
              @update:model-value="changeQuantity"
            />
          </view>
        </view>
      </view>
    </template>
    <template #right>
      <view class="swipe-action">
        <view class="remove-button" @click="removeProduct">
          <v-icon
            :custom-style="{ height: '74rpx', width: '52rpx' }"
            src="@/static/icons/cart-remove.svg"
          />
        </view>
      </view>
    </template>
  </wd-swipe-action>
</template>

<script setup lang="ts">
const props = defineProps<{
  product: CartVO;
  isEditing: boolean;
  editSelectingList: string[];
}>();

const emits = defineEmits<{
  refresh: [];
  'select-sku': [];
  'edit-select': [select: boolean, list: string[]];
}>();

const product = toRef(props, 'product');
const isEditing = toRef(props, 'isEditing');
const editSelectingList = toRef(props, 'editSelectingList');

const inventory = computed(() => {
  if (!product.value.inventory) return '无货';
  if (!product.value.sale_status) return '无货';
  if (product.value.inventory < product.value.quantity) {
    return `库存: ${product.value.inventory} 库存不足`;
  }
  if (product.value.inventory > 999) return '库存: 999+';
  return `库存: ${product.value.inventory}`;
});
const statusText = computed(() => {
  if (!product.value.sale_status) return '补货中';
  if (product.value.inventory === 0) return '补货中';
  if (product.value.status === 'DISABLED') return '已下架';
  return '';
});

const isSelected = computed(() => {
  if (isEditing.value) {
    return editSelectingList.value.includes(product.value.id);
  } else {
    return product.value.selected === 'SELECTED';
  }
});
const selectHandle = async () => {
  if (isEditing.value) {
    emits('edit-select', !isSelected.value, [product.value.id]);
  } else {
    const selected =
      product.value.selected === 'SELECTED' ? 'UNCHECK' : 'SELECTED';
    if (statusText.value && selected === 'SELECTED') return;
    const response = await $api.postCartEditSelects([
      { id: product.value.id, selected }
    ]);
    switch (response.__error) {
      case undefined:
        emits('refresh');
        break;
    }
  }
};
const removeProduct = async () => {
  const result = await uni.showModal({
    title: '提示',
    content: '确定删除该商品吗？'
  });
  if (!result.confirm) return;
  uni.showLoading({ mask: true });
  const response = await $api.postCartRemove([{ cart_id: product.value.id }]);
  switch (response.__error) {
    case undefined:
      // 这里交给 page 取消loading
      // uni.hideLoading();
      emits('refresh');
      uni.showToast({ title: '删除成功', icon: 'none' });
      break;
    default:
      uni.hideLoading();
  }
};
const changeQuantity = async (val: number | undefined) => {
  if (val === undefined) return;
  if (val === product.value.quantity) return;
  uni.showLoading({ mask: true });
  const response = await $api.getCartIdEditNum(product.value.id, {
    quantity: val
  });
  switch (response.__error) {
    case undefined:
      // 这里交给 page 取消loading
      // uni.hideLoading();
      emits('refresh');
      break;
    default:
      uni.hideLoading();
  }
};

const navigateToDetails = () => {
  uni.navigateTo({
    url: `/pages/product/product-details?id=${props.product.spu_id}`
  });
};
</script>

<style lang="scss" scoped>
.swipe-action {
  display: flex;
  align-items: stretch;
  height: 100%;
  padding-left: 24rpx;
  .remove-button {
    width: 100rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: red;
    border-radius: 0 16rpx 16rpx 0;
  }
}
.product {
  display: flex;
  align-items: stretch;
  .product-checkbox {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 12rpx;
  }
  .product-image {
    position: relative;
    .image-mask {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(255, 255, 255, 0.3);
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .product-status {
      padding: 0 30rpx;
      font-size: 24rpx;
      line-height: 44rpx;
      height: 44rpx;
      border-radius: 22rpx;
      color: #ffffff;
      background-color: rgba(0, 0, 0, 0.5);
    }
  }
  .product-info {
    flex: 1;
    min-width: 0;
    margin-left: 24rpx;
    .name {
      font-weight: bold;
      margin-bottom: 12rpx;
    }
    .spec-list {
      display: flex;
      flex-wrap: wrap;
      gap: 8rpx 16rpx;
      margin-bottom: 20rpx;
      .spec-item {
        padding: 4rpx 8rpx;
        border-radius: 4rpx;
        background-color: #f5f6fa;
        display: flex;
        align-items: center;
        gap: 24rpx;
        font-size: 22rpx;
      }
    }
    .inventory {
      font-size: 22rpx;
      color: #ff2f3b;
      margin-bottom: 12rpx;
    }
    .footer {
      display: flex;
      align-items: flex-end;
      justify-content: space-between;
    }
  }
}
</style>
